export const typewriter = {
  mounted(el, binding) {
    const options = {
      speed: 80, // 打字速度
      delay: 0, // 开始前的延迟
      cursor: true, // 是否显示光标
      pausable: false, // 是否可暂停
      onComplete: null, // 完成回调
      cursorHideDelay: 1000, // 光标消失延迟时间（毫秒）
      // 新增光标样式配置
      cursorStyle: {
        width: '2px',
        height: '1em',
        color: '#666', // 灰色
        blinkSpeed: 0.7 // 闪烁速度
      },
      ...binding.value
    };

    // 创建包装容器
    const wrapper = document.createElement('div');
    wrapper.style.cssText = 'display: inline-block; position: relative;';

    // 创建文本容器
    const textContainer = document.createElement('span');
    textContainer.className = 'typewriter-text';

    // 将原始元素的内容和属性转移到文本容器
    const text = el.textContent;
    textContainer.style.cssText = window.getComputedStyle(el).cssText;

    // 清空并设置包装容器
    el.textContent = '';
    el.style.cssText = 'display: inline-block;';
    el.appendChild(wrapper);
    wrapper.appendChild(textContainer);

    let index = 0;
    let timer = null;
    let cursorTimer = null;
    let isPaused = false;

    // 添加光标
    if (options.cursor) {
      const cursor = document.createElement('span');
      cursor.className = 'typewriter-cursor';

      // 设置光标样式
      cursor.style.cssText = `
        position: absolute;
        top: 4px;
        right: -4px;
        width: ${options.cursorStyle.width};
        height: ${options.cursorStyle.height};
        background-color: ${options.cursorStyle.color};
        display: inline-block;
        opacity: 1;
      `;

      wrapper.appendChild(cursor);

      // 添加光标动画样式
      const styleId = 'typewriter-cursor-style';
      if (!document.getElementById(styleId)) {
        const style = document.createElement('style');
        style.id = styleId;
        style.textContent = `
          .typewriter-cursor {
            animation: blink 0.7s infinite;
          }
          @keyframes blink {
            0%, 100% { opacity: 1; }
            50% { opacity: 0; }
          }
        `;
        document.head.appendChild(style);
      }
    }

    // 隐藏光标
    const hideCursor = () => {
      const cursor = wrapper.querySelector('.typewriter-cursor');
      if (cursor) {
        cursor.style.display = 'none';
      }
    };

    // 开始打字函数
    const startTyping = () => {
      timer = setInterval(() => {
        if (isPaused) return;

        if (index < text.length) {
          textContainer.textContent = text.substring(0, index + 1);
          index++;
        } else {
          clearInterval(timer);
          // 打字完成后1秒隐藏光标
          if (options.cursor) {
            cursorTimer = setTimeout(hideCursor, options.cursorHideDelay);
          }
          if (typeof options.onComplete === 'function') {
            options.onComplete();
          }
        }
      }, options.speed);
    };

    // 暂停打字
    const pause = () => {
      isPaused = true;
      const cursor = wrapper.querySelector('.typewriter-cursor');
      if (cursor) {
        cursor.style.opacity = '0.5';
        cursor.style.animation = 'none';
      }
    };

    // 继续打字
    const resume = () => {
      isPaused = false;
      const cursor = wrapper.querySelector('.typewriter-cursor');
      if (cursor) {
        cursor.style.opacity = '1';
        cursor.style.animation = 'blink 0.7s infinite';
      }
    };

    // 如果支持暂停，添加点击事件
    if (options.pausable) {
      wrapper.addEventListener('click', () => {
        isPaused ? resume() : pause();
      });
    }

    // 设置延迟启动
    setTimeout(startTyping, options.delay);

    // 在组件销毁时清理
    el._typewriterCleanup = () => {
      clearInterval(timer);
      clearTimeout(cursorTimer);
      const styleElement = document.getElementById('typewriter-cursor-style');
      if (styleElement) {
        styleElement.remove();
      }
    };
  },

  unmounted(el) {
    if (el._typewriterCleanup) {
      el._typewriterCleanup();
    }
  }
};
